import { View } from "@tarojs/components"
import { useEffect, useRef, useState } from "react"
import Taro from '@tarojs/taro'
import avatarImg from '../../../assets/image/avatar.png'
import carImag from '../../../assets/image/card-img.png'
import './index.less'
import CollectionCard from "../collection-card"
import { collectionType } from "../type"

const listData: Array<collectionType> = [
    {
        id: '1',
        publisher: {
            avatar: avatarImg,
            name: '吴亦凡'
        },
        content: {
            text: '绿茶打扮',
            clothes: [carImag, carImag, carImag, carImag, carImag],
            like: 5
        }
    },
    {
        id: '2',
        publisher: {
            avatar: avatarImg,
            name: '刘亦菲'
        },
        content: {
            text: '绿茶打扮',
            clothes: [carImag, carImag, carImag, carImag, carImag],
            like: 45
        }
    },
    {
        id: '3',
        publisher: {
            avatar: avatarImg,
            name: '景甜'
        },
        content: {
            text: '韩式风潮',
            clothes: [carImag, carImag, carImag, carImag, carImag],
            like: 41
        }
    },
]

function CollectionSquare() {
    const [height, setHeight] = useState(0)
    const [collectionData, setCollectionData] = useState<Array<collectionType> | []>([])

    const ref = useRef()

    useEffect(() => {
        if (ref.current) {
            const query = Taro.createSelectorQuery()
            query.select('.clothes').boundingClientRect()
            query.selectViewport().scrollOffset()
            query.exec((res) => {
                setHeight((res[1].scrollWidth - 60 - 1 * 3) / 4)
            })
        }
        if (collectionData.length == 0) {
            setCollectionData(listData)
        }
    }, [ref])

    Taro.eventCenter.on('setCollection', ({ id, val }) => {
        const i = collectionData.findIndex((item: { id: string }) => item.id == id)
        if (i > -1) {
            collectionData[i] = val
            setCollectionData([...collectionData])
        }
    })

    return <View className='collection-square' ref={ref}>
        <View>
            {
                collectionData.map((v, k) => {
                    return <CollectionCard height={height} collection={v} key={k} />
                })
            }
        </View>
    </View>
}

export default CollectionSquare